﻿using Max.PH5_2006.ShoppingSite.Domain;
using Max.PH5_2006.ShoppingSite.DTO;
using Max.PH5_2006.ShoppingSite.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;

namespace Max.PH5_2006.ShoppingSite.API.Controllers
{
    [Route("goods")]
    [ApiController]
    public class GoodsController : ControllerBase
    {
        IGoodsService _service;

        public GoodsController(IGoodsService service)
        {
            _service = service;
        }
        [HttpGet]
        public IActionResult GetQuery(string? key="",string sortField = "title",string sortValue ="asc", int pageIndex = 1, int pageSize = 10)
        {
            ResponseResultDto result = new();

            if (pageSize <= 0)
                pageSize = 10;

            #region //用封装的表达式树，委托方式查询、排序
            Expression<Func<GoodsEntity, bool>> expression = null;
            expression = x => x.Title.Contains(key ?? "");


            //是否升序
            bool isAsc = sortValue.ToLower().Equals("asc") ? true : false;
            //排序字段
            Expression<Func<GoodsEntity, object>> sortFunc = null;
            sortFunc = sortField.ToLower() switch
            {
                "title" => x => x.Title,
                "price" => x => x.SalePrice,
                _ => x => x.CreatedTime,
            };

            var data = _service.Query(expression, sortFunc, isAsc, pageIndex, pageSize, out int count);


            //上面的switch的简写方式，是如下的详细
            //switch (sortField.ToLower())
            //{
            //    case "title":
            //        sortFunc = x => x.Title;
            //        break;
            //    case "price":
            //        sortFunc = x => x.SalePrice;
            //        break;
            //    default:
            //        sortFunc = x => x.CreatedTime;
            //        break;
            //}
            #endregion


            #region //用原始的方法查询、排序

            /*
            var list = _service.Query();
            list = list.Where(x => x.Title.Contains(key??"")).ToList();

            int count = list.Count;
            var data = list.Skip((pageIndex-1)*pageSize).Take(pageSize).ToList();


            //价格排序
            if(sortField.ToLower().Equals("price"))
            {
                //价格的升序
                if(sortValue.ToLower().Equals("asc"))
                {
                    data = data.OrderBy(x => x.SalePrice).ToList();
                }
                else
                {
                    //价格的降序
                    data = data.OrderByDescending(x => x.SalePrice).ToList();
                }
            }
            //根据标题名称排序
            else if (sortField.ToLower().Equals("name"))
            {
                if (sortValue.ToLower().Equals("asc"))
                {
                    data = data.OrderBy(x => x.Title).ToList();
                }
                else
                {
                    data = data.OrderByDescending(x => x.Title).ToList();
                }
            }
            */

            #endregion



            result.Data = new { items= data, total = count };

            return Ok(result);
        }


        [HttpGet("id")]
        public IActionResult GetDetail(string id)
        {
            ResponseResultDto response = new();

            var data = _service.Query().Where(x => id.Equals(x.Id.ToString())).FirstOrDefault();
            //var data = _service.QueryById(id);
            response.Data = data;

            return Ok(response);
        }

        [HttpPost]
        public IActionResult Post(GoodsEntity entity)
        {
            ResponseResultDto response = new();

            if (string.IsNullOrEmpty(entity.Title))
            {
                response.Code = Domain.Shared.ResponseResultStatue.请求失败;
                response.Message = "参数无效！商品名称不能为空";
                return Ok(response);
            }

            response.Data =  _service.Add(entity);

            return Ok(response);
        }





        [HttpPost("car/add2")]
        public IActionResult PostAddCar(CarEntityDto dto)
        {


            //连接到redis服务器
            var redis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            var list = redis.Get<List<CarEntityDto>>(dto.MemberId.ToString());
            
            if (list == null)
                list = new List<CarEntityDto>();

            list.Add(dto);

            redis.Set(dto.MemberId.ToString(),list);



            return Ok();
        }


        #region 购物车相关

        //添加购物车
        [HttpPost("car/add")]
        public IActionResult AddCar(CarEntityDto dto)
        {
            ResponseResultDto result = new();

           var redis =  new CSRedis.CSRedisClient("127.0.0.1:6379");

            //将商品放入redis   ---- set
            //将商品从redis中拿出来    ---- get
            var key = dto.MemberId.ToUpper();

            //先把redis里的数据取出来
            List<CarEntityDto> list = redis.Get<List<CarEntityDto>>(key);
            
            //第一次使用的时候，redis中的list为null
            if (list == null)
                list = new List<CarEntityDto>();

            //将要加入购物车的数据放到这些原来的集合中
            //list.Add(dto);
            //如果添加同样的商品的情况下，则只修改商品的数量

            var m = list.Where(x => x.GoodsName.Equals(dto.GoodsName)).FirstOrDefault();
            if(m == null)
            {
                //表示原来redis里没有待加入的商品
                list.Add(dto);
            }
            else
            {
                //原来redis里有待加入的商品，则只修改数量
                m.GoodsNumber += dto.GoodsNumber;
            }

            //将新的数据更新到缓存
            redis.Set(key, list);


            return Ok(result);
        }

        //显示购物车
        [HttpGet("car/list")]
        public IActionResult GetCarList(string key)
        {
            ResponseResultDto result = new();

            var redis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            var data = redis.Get<List<CarEntityDto>>(key.ToUpper());

            //将redis里的数据和商品表数据联查，获取图片
           var q = from a in data
            join b in _service.Query() on a.GoodsName equals b.Title
            select new
            {
                a.GoodsId,
                a.GoodsName,
                a.GoodsNumber,
                a.GoodsPrice,
                a.MemberId,
                b.CoverImg
            };

            result.Data = q;

            return Ok(result);
        }


        //修改购物车数量
        [HttpPost("car/update")]
        public IActionResult UpdateCarNumber(CarEntityDto dto)
        {
            ResponseResultDto result = new();

            var key = dto.MemberId.ToUpper();
            //修改谁的缓存数据 -- 会员ID
            var redis = new CSRedis.CSRedisClient("127.0.0.1:6379");
            var data = redis.Get<List<CarEntityDto>>(key);

            //修改哪条商品  --  商品ID
            var m = data.Where(x => x.GoodsName.Equals(dto.GoodsName)).FirstOrDefault();

            //修改这条商品的具体数量  -- 更新后的数量
            if(m!=null)
                m.GoodsNumber = dto.GoodsNumber;


            //修改完成后，更新缓存
            redis.Set(key, data);

            return Ok(result);
        }


        [HttpDelete("car/delete")]
        public IActionResult DeleteCar(List<CarEntityDto> dtos)
        {
            ResponseResultDto response = new();
            //删除 - 是指从购物车缓存中删除
            //所以：1、先拿到缓存
            var redis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            string key = dtos[0].MemberId.ToUpper();
            //判断redis里面，这个key是否存在
            if (!redis.Exists(key)) {
                response.Message = "无效的请求";
                return Ok(response);
            }
            var data = redis.Get<List<CarEntityDto>>(key);

            //2、去缓存数据里找（如果是单删除，就不用循环找）
            foreach (var dto in dtos)
            {
                var m = data.Where(x => x.GoodsName.Equals(dto.GoodsName)).FirstOrDefault();

                //3、找到了就删除
                if (m != null)
                    data.Remove(m);
            }

            //4、更新缓存
            redis.Set(key, data);

            return Ok(response);
        }

        #endregion

    }


}
